package ua.org.nuos.sdms.clientgui.client.view.tabs;

import com.vaadin.data.Validator;
import com.vaadin.ui.*;
import ua.org.nuos.sdms.clientgui.client.components.factory.ButtonFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.FormFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.LayoutFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.SeparatorFactory;
import ua.org.nuos.sdms.clientgui.client.components.fieldFactory.GroupFieldFactory;
import ua.org.nuos.sdms.clientgui.client.components.tabs.DataTab;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.*;
import ua.org.nuos.sdms.clientgui.client.listeners.EntityChangedListener;
import ua.org.nuos.sdms.clientgui.client.model.EntityBeanItem;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.Group;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 18.03.12
 * Time: 19:12
 * To change this template use File | Settings | File Templates.
 */
public class GroupConfigTab extends DataTab implements EntityChangedListener<Group> {

    public static final String ID = "GroupConfigTab";
    public static final String CONTENT_WIDTH = "550";
    private static final String caption = "Профиль группы";

    private EntityBeanItem<Group> beanItem;
    private Form form;
    private Layout refuseLayout, removeLayout, detachLayout;
    private Button save, cancel;

    public GroupConfigTab() {
        super(caption);
        init();
    }

    private void init() {
        AppProxy.getInstance().getComponentLocator().addTab(ID, this);
        AppProxy.getInstance().getModelLocator().getGroupContainer().addListener(this);

        Group group = filterGroup(AppProxy.getInstance().getModelLocator().getGroup());
        beanItem = new EntityBeanItem<Group>(group);
        form = FormFactory.getForm(new GroupFieldFactory(), beanItem, new String[]{"name", "organisation", "about"});

        initComponents();
    }

    private void initComponents() {
        save = ButtonFactory.getButton("Сохранить", getSaveConfigClickListener());
        ButtonFactory.setButtonColorStyle(save, ButtonFactory.Color.GREEN);
        cancel = ButtonFactory.getButton("Очистить", getCancelConfigClickListener());
        Layout buttons = LayoutFactory.getHLayout(save, cancel);

        Button remove = ButtonFactory.getButton("Удалить группу", getRemoveClickListener());
        ButtonFactory.setButtonColorStyle(remove, ButtonFactory.Color.RED);
        String removeMessage = "<b>Удаление группы безвозвратно уничтожит все данные группы. " +
                "Одумайтесь, пока не позно.</b>";
        removeLayout = createMessageButtonLayout(removeMessage, remove);

        Button detach = ButtonFactory.getButton("Выйти из группы", GlobalBoard.ID, DetachCurrentUserFromGroupEvent.class);
        ButtonFactory.setButtonColorStyle(detach, ButtonFactory.Color.RED);
        String detachMessage = "<b>Выход из группы безвозвратно уничтожит все Ваши записи в группе. " +
                "Одумайтесь, пока не позно.</b>";
        detachLayout = createMessageButtonLayout(detachMessage, detach);

        Button refuse = ButtonFactory.getButton("Отказаться от лидерства", GlobalBoard.ID, RefuseFromLeaderTypeEvent.class);
        String refuseMessage = "<b>Отказ от лидерства оставит управление группой Вашим одногруппникам. Вы готовы пойти на этот шаг? " +
                "Одумайтесь, пока не позно.</b>";
        refuseLayout = createMessageButtonLayout(refuseMessage, refuse);
        defineVisibility();

        VerticalLayout content = new VerticalLayout();
        content.setWidth(CONTENT_WIDTH);
        content.setSpacing(true);
        content.addComponent(new Label("<h2>Параметры групы:</h2>", Label.CONTENT_XHTML));
        content.addComponent(form);
        content.addComponent(buttons);
        content.addComponent(removeLayout);
        content.addComponent(detachLayout);
        content.addComponent(refuseLayout);
        content.setComponentAlignment(buttons, Alignment.BOTTOM_RIGHT);

        setDataContainer(content);
    }

    private Button.ClickListener getSaveConfigClickListener() {
        return new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                try {
                    form.commit();
                    Group group = beanItem.getBean();
                    AppProxy.getInstance().getController(GlobalBoard.ID).fire(new UpdateGroupEvent(group));
                } catch (Validator.InvalidValueException e) {
                    Logger.getAnonymousLogger().log(Level.WARNING, "validation exception", e);
                }
            }
        };
    }

    private Button.ClickListener getCancelConfigClickListener() {
        return new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                Group group = filterGroup(AppProxy.getInstance().getModelLocator().getGroup());
                beanItem.setBean(group);
                form.discard();
            }
        };
    }

    private Button.ClickListener getRemoveClickListener() {
        return new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                AppProxy.getInstance().getController(GlobalBoard.ID).fire(new RemoveGroupEvent(beanItem.getBean().getId()));
            }
        };
    }

    @Override
    public void changed(EntityChangedEvent<Group> entityChangedEvent) {
        Group group = filterGroup(entityChangedEvent.getEntityContainer().getEntity());
        beanItem.setBean(group);
        defineVisibility();
    }

    private Group filterGroup(Group group) {
        if (group == null) {
            group = new Group();
        }
        return group;
    }

    private Layout createMessageButtonLayout(String message, Button button) {
        Label removeMessage = new Label(message, Label.CONTENT_XHTML);
        HorizontalLayout layout = new HorizontalLayout();
        layout.setWidth("100%");
        layout.setSpacing(true);
        layout.addComponent(removeMessage);
        layout.addComponent(button);
        layout.setExpandRatio(removeMessage, 1.f);
        layout.setComponentAlignment(button, Alignment.BOTTOM_RIGHT);

        VerticalLayout verticalLayout = new VerticalLayout();
        verticalLayout.setWidth("100%");
        verticalLayout.addComponent(SeparatorFactory.getHorizontal());
        verticalLayout.addComponent(layout);
        return verticalLayout;
    }

    private void defineVisibility() {
        Group group = AppProxy.getInstance().getModelLocator().getGroup();
        boolean isLeaderVisible = false, isVisible = false;
        if (group != null) {
            UserInGroup.Type type = AppProxy.getInstance().getServiceLocator().getClientBean()
                    .findCurrentUserInGroupStatus(group.getId());
            isLeaderVisible = UserInGroup.Type.LEADER.equals(type);
            isVisible = true;
        }
        refuseLayout.setVisible(isLeaderVisible);
        removeLayout.setVisible(isLeaderVisible);
        detachLayout.setVisible(isVisible);

        form.setEnabled(isLeaderVisible);
        save.setEnabled(isLeaderVisible);
        cancel.setEnabled(isLeaderVisible);
    }
}
